package com.ahdms.es.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.Properties;

/**
 * @author qinxiang
 * @date 2021-04-13 16:00
 */
public class NioUtils {

    private static Logger log = LoggerFactory.getLogger(NioUtils.class);

    public static byte[] fileToBytes(String filePath){
        try {
            return Files.readAllBytes(Paths.get(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static InputStream toInputStream(byte[] bytes){
        return Optional.ofNullable(bytes).map(ByteArrayInputStream::new).orElse(null);
    }

    public static InputStream getResourceAsStream(String name) {
        if (name != null && !name.isEmpty()) {
            String name0 = name.charAt(0) == '/' ? name.substring(1) : name;
            Object in = null;

            try {
                in = NioUtils.class.getClassLoader().getResourceAsStream(name0);
                if (in == null) {
                    File file = new File(name0);
                    if (!file.exists() && name != name0) {
                        file = new File(name);
                    }

                    log.info("无法按ClassLoader.getResourceAsStream读取，尝试按磁盘文件方式读取：{}", file);
                    in = new FileInputStream(file);
                }
            } catch (FileNotFoundException var4) {
                log.warn("无法读取：{}", name, var4);
            }

            return (InputStream)in;
        } else {
            return null;
        }
    }

    public static Properties loadProperties(String name) {
        Properties props = new Properties();
        try {
            InputStream in = getResourceAsStream(name);
            Throwable var3 = null;

            try {
                if (in != null) {
                    props.load(in);
                }
            } catch (Throwable var13) {
                var3 = var13;
                throw var13;
            } finally {
                if (in != null) {
                    if (var3 != null) {
                        try {
                            in.close();
                        } catch (Throwable var12) {
                            var3.addSuppressed(var12);
                        }
                    } else {
                        in.close();
                    }
                }
            }

            return props;
        } catch (IOException var15) {
            throw new IllegalArgumentException(var15);
        }
    }

}
